<?php
namespace app\admin\Controller;

use app\admin\Model\TermModel;
use cmf\controller\AdminBaseController;

use think\db\Where;
use think\Validate;
Class TermController extends AdminBaseController{
    public function index() {
        extract(input());
        $where = new Where;
        if(isset($term_name) && !empty($term_name)){
            $where['term_name'] = ['like','%'.$term_name.'%'];
        }
        $data = TermModel::where($where)
            ->order('id Desc')
            ->paginate(3,false,['query'=>input()]);
        $page = $data->render();
        return $this->fetch('',[
            'data' => $data,
            'page' => $page,
        ]);
    }
    public function add() {
        return $this->fetch();
    }
    public function addPost() {
        $data = input();
        $rule = [
            'term_name' => 'require',
        ];
        $msg = [
            'term_name.require' => '学期名称不能为空',
        ];
        $validate = new Validate($rule, $msg);
        $result = $validate->check($data);
        if (true !== $result) {
            $this->error($validate->getError());
        }
        $add = TermModel::create($data);
        if ($add){
            return json(['code' => 1 ,'msg' => '添加成功']);
        }else{
            return json (['code' => 2 ,'msg' => '添加失败']);
        }
    }
    public function edit(){
        $id = input('id');
        $data = TermModel::where('id',$id)->find();
        $this->assign('data',$data);
        $this->assign('id',$id);
        return $this->fetch();
    }
    public function editPost(){
        $data = input();
        $rule = [
            'term_name'  => 'require',
        ];
        $msg = [
            'term_name.require' => '学期名称不能为空',
        ];
        $validate = new Validate($rule, $msg);
        $result   = $validate->check($data);
        if (true!==$result){
            $this->error($validate->getError());
        }
        $edit = TermModel::where('id',$data['id'])->update($data);
        if ($edit) {
            return json(['code' => 1 , 'msg' => '修改成功']);
        }else{
            return json(['code' => 2 , 'msg' => '修改失败']);
        }
    }
    public function delete () {
        $id = input('id');
        $del = TermModel::destroy($id);
        if($del){
            return json(['code' => 1 , 'msg' =>'删除成功']);
        }else{
            return json (['code' => 2 , 'msg' => '删除失败']);
        }
    }
    public function delAll() {
        $ids = input('ids/a');
        $del = TermModel::destroy($ids);
        if($del){
            $this->success('删除成功','Term/index');
        }else{
            $this->error('删除失败','Term/index');
        }
    }
}